<div class="query-page-wrapper">
  <div class="container">
    <overlay ng-if="canCreateQuery === false && query.isNew()">
      You don't have permission to create new queries on any of the data sources available to you. You can either
      <a href="queries">browse existing queries</a>, or ask for additional permissions from your Redash admin.
    </overlay>
    <overlay ng-if="noDataSources && currentUser.isAdmin">
      Looks like no data sources were created yet (or none of them available to the group(s) you're member of). Please create one
      first, and then start querying.
      <br/>
      <a href="data_sources/new" class="btn btn-primary">Create Data Source</a>
      <a href="groups" class="btn btn-default">Manage Group Permissions</a>
    </overlay>
    <overlay ng-if="noDataSources && !currentUser.isAdmin">
      Looks like no data sources were created yet (or none of them available to the group(s) you're member of). Please ask your
      Redash admin to create one first.
    </overlay>

    <alert-unsaved-changes ng-if="canEdit" is-dirty="isDirty"></alert-unsaved-changes>

    <div class="p-b-10 m-l-0 m-r-0 page-header--new page-header--query">
      <div class="page-title p-0">
        <div class="d-flex flex-nowrap align-items-center">
          <favorites-control ng-if="!query.isNew()" item="query"></favorites-control>
          <h3>
            <edit-in-place class="m-r-5" is-editable="canEdit" on-done="saveName"
              ignore-blanks="true" value="query.name" editor="'input'"></edit-in-place>
            <query-tags-control
              class="query-tags" ng-class="{'query-tags__empty': query.tags.length == 0}"
              tags="query.tags" is-draft="query.is_draft" is-archived="query.is_archived"
              can-edit="isQueryOwner" get-available-tags="loadTags" on-edit="saveTags"></query-tags-control>
          </h3>

          <span class="flex-fill">&nbsp;</span>

          <div class="p-0 source-control text-right text-nowrap align-self-start m-t-5">
            <button class="btn btn-default btn-publish" ng-click="togglePublished()" ng-if="query.is_draft && query.id != undefined && (isQueryOwner || currentUser.hasPermission('admin'))">
              <span class="fa fa-paper-plane"></span> Publish
            </button>

            <span ng-show="query.id && canViewSource">
              <a ng-show="!sourceMode" ng-href="{{query.getUrl(true, selectedTab)}}" class="btn btn-default btn--showhide">
                <i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit Source</i>
              </a>
              <a
                ng-show="sourceMode"
                ng-href="{{query.getUrl(false, selectedTab)}}"
                class="btn btn-default btn--showhide"
                data-test="QueryPageShowDataOnly"
              >
                <i class="fa fa-table" aria-hidden="true"></i> Show Data Only</i>
              </a>
            </span>

            <div ng-if="query.id != undefined" class="btn-group query-actions-menu" role="group" uib-dropdown>
              <button class="btn btn-default dropdown-toggle hidden-xs" uib-dropdown-toggle>
                <span class="zmdi zmdi-more"></span>
              </button>
              <ul class="dropdown-menu pull-right" uib-dropdown-menu>
                <li ng-class="{'disabled': query.id === undefined || !canForkQuery() }">
                  <a ng-click="duplicateQuery()"> Fork <i class="fa fa-external-link"></i></a>
                </li>
                <li class="divider" ng-if="query.is_archived"></li>
                <li ng-if="!query.is_archived && query.id != undefined && (isQueryOwner || currentUser.hasPermission('admin'))">
                  <a ng-click="archiveQuery()">Archive</a>
                </li>
                <li ng-if="!query.is_archived && query.id != undefined && (isQueryOwner || currentUser.hasPermission('admin')) && showPermissionsControl">
                  <a ng-click="showManagePermissionsModal()">Manage Permissions</a>
                </li>
                <li ng-if="!query.is_draft && query.id != undefined && (isQueryOwner || currentUser.hasPermission('admin'))">
                  <a ng-click="togglePublished()">Unpublish</a>
                </li>
                <li class="divider" ng-if="!query.is_archived"></li>
                <li ng-if="query.id != undefined">
                  <a ng-click="showApiKey()">Show API Key</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <query-tags-control
          class="query-tags__mobile" ng-class="{'query-tags__empty': query.tags.length == 0}"
          tags="query.tags" is-draft="query.is_draft" is-archived="query.is_archived"
          can-edit="isQueryOwner" get-available-tags="loadTags" on-edit="saveTags"></query-tags-control>
      </div>
    </div>
  </div>
  <main class="query-fullscreen">
    <nav resizable r-directions="['right']" r-flex="true" resizable-toggle toggle-shortcut="Alt+Shift+D, Alt+D">
      <div class="editor__left__data-source">
        <ui-select ng-model="query.data_source_id" remove-selected="false" ng-disabled="!isQueryOwner || !sourceMode"
          on-select="updateDataSource()" data-test="SelectDataSource">
          <ui-select-match placeholder="Select Data Source..." class="align-items-center">
            <img ng-src="/static/images/db-logos/{{$select.selected.type}}.png" width="20" height="20" style="vertical-align: top">
            {{$select.selected.name}}
          </ui-select-match>
          <ui-select-choices repeat="ds.id as ds in dataSources | filter:$select.search">
            <img ng-src="/static/images/db-logos/{{ds.type}}.png" width="20" height="20" class="m-r-5">{{ds.name}}
          </ui-select-choices>
        </ui-select>
      </div>

      <div class="editor__left__schema" ng-if="sourceMode">
        <schema-browser class="schema-container" schema="schema" on-refresh="refreshSchema()"></schema-browser>
      </div>
      <div ng-if="!sourceMode" style="flex-grow: 1;">&nbsp;</div>

      <div class="query-metadata query-metadata--description" ng-if="!query.isNew()">
        <edit-in-place is-editable="canEdit" on-done="saveDescription" editor="'textarea'" placeholder="'Add description'" ignore-blanks='false'
          value="query.description" markdown="true">
        </edit-in-place>
      </div>

      <div class="query-metadata query-metadata--history" ng-if="!query.isNew()">
        <table>
          <tr>
            <td>
              <img ng-src="{{ query.user.profile_image_url }}" class="profile__image_thumb" />
              <strong class="meta__name" ng-class="{'text-muted': query.user.is_disabled}">{{query.user.name}}</strong>
            </td>
            <td class="text-right">
              created
              <strong>
                <rd-time-ago value="query.created_at"></rd-time-ago>
              </strong>
            </td>
          </tr>
          <tr>
            <td>
              <img ng-src="{{ query.last_modified_by.profile_image_url }}" class="profile__image_thumb" />
              <strong class="meta__name" ng-class="{'text-muted': query.last_modified_by.is_disabled}">{{query.last_modified_by.name}}</strong>
            </td>
            <td class="text-right">
              updated
              <strong>
                <rd-time-ago value="query.updated_at"></rd-time-ago>
              </strong>
            </td>
          </tr>
          <tr>
            <td class="p-t-15">
              <span class="query-metadata__property">
                <span class="zmdi zmdi-refresh"></span> Refresh Schedule</span>
            </td>
            <td class="p-t-15 text-right">
              <schedule-phrase ng-click="editSchedule()" is-link="true" schedule="query.schedule" is-new="query.isNew()" />
            </td>
          </tr>
        </table>
      </div>
    </nav>

    <div class="content">
      <div class="flex-fill p-relative">
        <div class="p-absolute d-flex flex-column p-l-15 p-r-15" style="left: 0; top: 0; right: 0; bottom: 0; overflow: auto">
          <div class="row editor" resizable r-directions="['bottom']" r-flex="true" resizable-toggle
               style="min-height: 11px; max-height: 70vh;" ng-if="sourceMode">
            <query-editor
              style="width: 100%; height: 100%;"
              query-text="query.query"
              schema="schema"
              syntax="dataSource.syntax"
              can-edit="canEdit"
              is-dirty="isDirty"
              is-query-owner="isQueryOwner"
              update-data-source="updateDataSource"
              execute-query="executeQuery"
              query-executing="queryExecuting"
              can-execute-query="canExecuteQuery()"
              listen-for-resize="listenForResize"
              listen-for-editor-command="listenForEditorCommand"
              save-query="saveQuery"
              update-query="updateQuery"
              update-selected-query="updateSelectedQuery"
              add-new-parameter="addNewParameter"
              data-data-source="dataSource"
              data-data-sources="dataSources"></query-editor>
          </div>

          <div class="row query-metadata__mobile">
            <img ng-src="{{ query.user.profile_image_url }}" class="profile__image_thumb">
            <div class="flex-fill m-r-10">
              <strong class="meta__name" ng-class="{'text-muted': query.user.is_disabled}">{{query.user.name}}</strong>
              created <rd-time-ago value="query.created_at"></rd-time-ago>
            </div>

            <img ng-src="{{ query.last_modified_by.profile_image_url }}" class="profile__image_thumb">
            <div class="flex-fill m-r-10">
              <strong class="meta__name" ng-class="{'text-muted': query.last_modified_by.is_disabled}">{{query.last_modified_by.name}}</strong>
              updated <rd-time-ago value="query.updated_at"></rd-time-ago>
            </div>

            <div>
              <span class="query-metadata__property">Refresh schedule:</span>
              <schedule-phrase ng-click="editSchedule()" is-link="true" schedule="query.schedule" is-new="query.isNew()" />
            </div>
          </div>

          <section class="flex-fill p-relative t-body query-visualizations-wrapper">
            <div class="d-flex flex-column p-b-15 p-absolute static-position__mobile" style="left: 0; top: 0; right: 0; bottom: 0;">
              <div class="p-t-15 p-b-5" ng-if="query.hasParameters()">
                <parameters parameters="query.getParametersDefs()" editable="sourceMode && canEdit" disable-url-update="query.isNew()"
                  on-values-change="executeQuery" on-pending-values-change="applyParametersChanges" on-parameters-edit="onParametersUpdated"></parameters>
              </div>
              <!-- Query Execution Status -->

              <div class="query-alerts">
                <div class="alert alert-info m-t-15" ng-if="queryResult.getStatus() == 'processing'">
                  Executing query&hellip;
                  <rd-timer from="queryResult.getUpdatedAt()"></rd-timer>
                  <button type="button" class="btn btn-warning btn-xs pull-right" ng-disabled="cancelling" ng-click="cancelExecution()">Cancel
                  </button>
                </div>
                <div class="alert alert-info m-t-15" ng-if="queryResult.getStatus() == 'loading-result'">
                  Loading results&hellip;
                  <rd-timer from="queryResult.getUpdatedAt()"></rd-timer>
                </div>
                <div class="alert alert-info m-t-15" ng-if="queryResult.getStatus() == 'waiting'">
                  Query in queue&hellip;
                  <rd-timer from="queryResult.getUpdatedAt()"></rd-timer>
                  <button type="button" class="btn btn-warning btn-xs pull-right" ng-disabled="cancelling" ng-click="cancelExecution()">Cancel
                  </button>
                </div>
                <div class="alert alert-danger m-t-15" ng-if="queryResult.getError()">
                  Error running query:
                  <strong>{{queryResult.getError()}}</strong>
                </div>
              </div>
              <!-- End of Query Execution Status -->

              <!-- tabs and data -->
              <div ng-if="showDataset" class="flex-fill p-relative">
                <div class="d-flex flex-column p-absolute static-position__mobile" style="left: 0; top: 0; right: 0; bottom: 0;">
                  <div class="p-10" ng-show="showLog">
                    <p>Log Information:</p>
                    <p class="query-log-line" ng-repeat="l in queryResult.getLog() track by $index">{{l}}</p>
                  </div>
                  <ul class="tab-nav" data-test="QueryPageVisualizationTabs">
                    <rd-tab ng-if="!query.visualizations.length" tab-id="table" name="Table" base-path="query.getUrl(sourceMode)"></rd-tab>
                    <rd-tab ng-repeat="vis in query.visualizations | orderBy:'id'" tab-id="{{vis.id}}" name="{{vis.name}}" base-path="query.getUrl(sourceMode)">
                      <span class="remove hidden-xs" ng-click="deleteVisualization($event, vis)" ng-if="canEdit && !($first && (vis.type === 'TABLE'))">
                        <i class="zmdi zmdi-close"></i>
                      </span>
                    </rd-tab>
                    <li class="rd-tab tab-new-vis">
                      <a ng-click="openVisualizationEditor()" class="btn btn-default" ng-if="canEdit" data-test="NewVisualization">
                        <i class="zmdi zmdi-plus"></i> New Visualization</a>
                    </li>
                  </ul>
                  <div ng-if="selectedVisualization && queryResult" class="query__vis m-t-15 p-b-15 scrollbox" data-test="QueryPageVisualization{{ selectedVisualization.id }}">
                    <visualization-renderer visualization="selectedVisualization" query-result="queryResult" context="'query'"></visualization-renderer>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
      <div class="bottom-controller-container" ng-if="showDataset">
        <div class="bottom-controller">
          <edit-visualization-button
            ng-if="!query.isNew() && canEdit"
            open-visualization-editor="openVisualizationEditor"
            selected-tab="selectedTab">
          </edit-visualization-button>

          <query-control-dropdown
            query="query"
            query-result="queryResult"
            query-executing="queryExecuting"
            show-embed-dialog="showEmbedDialog"
            embed="embed"
            apiKey="apiKey"
            selected-tab="selectedTab"
            open-add-to-dashboard-form="openAddToDashboardForm">
          </query-control-dropdown>

          <span class="query-metadata__bottom" ng-if="queryResult.getData()">
            <span class="query-metadata__property">
              <strong>{{queryResult.getData().length}}</strong>
              <ng-pluralize count="queryResult.getData().length" when="{'0': ' rows', 'one': ' row', 'other': ' rows'}"></ng-pluralize>
            </span>
            <span class="query-metadata__property">
              <strong ng-show="!queryExecuting">{{queryResult.getRuntime() | durationHumanize}}</strong>
              <span ng-show="queryExecuting">Running&hellip;</span>
              <span class="hidden-xs">runtime</span>
            </span>
            <span class="query-metadata__property" ng-if="queryResult.query_result.data.metadata.data_scanned">Data Scanned
              <strong>{{ queryResult.query_result.data.metadata.data_scanned | prettySize}}</strong>
            </span>
          </span>

          <div>
            <span class="query-metadata__property hidden-xs">
              <span class="hidden-xs">Updated </span>
              <rd-time-ago value="queryResult.query_result.retrieved_at"></rd-time-ago>
            </span>

            <button
              ng-if="!sourceMode"
              ng-disabled="queryExecuting || !canExecuteQuery()"
              class="m-l-5 btn btn-primary"
              title="Refresh Dataset"
              ng-click="executeQuery()"
              data-test="ExecuteButton"
            >
              <span class="zmdi zmdi-play"></span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>
